package cn.lopr.im.android.db.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import cn.lopr.im.android.bean.HomeDialogueBean;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.db.entity.HomeDialogue;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.db.helper.CommonDaoUtils;
import cn.lopr.im.android.db.helper.DaoUtilsStore;
import cn.lopr.im.android.mvp.view.activities.MainActivity;
import cn.lopr.im.android.utils.DateUtil;

/**
 * @author shuangyang7
 * @date 2021/1/3 15:08
 */
public class MessageDaoService {
    static CommonDaoUtils<Message> messageDao = DaoUtilsStore.getInstance().getMessageDaoUtils();
    static CommonDaoUtils<HomeDialogue> homeDialogueDao = DaoUtilsStore.getInstance().getHomeDialogueUtils();

    public static List<Message> getMessage(String friendPhone, int type) {
        String[] param = {type + "", friendPhone, MainActivity.user.getPhone(), friendPhone};
        String sql = "WHERE type=? AND FROM_USER=? OR FROM_USER=? AND TO_USER=? ORDER BY DATE";
        return messageDao.queryByNativeSql(sql, param);
    }

    public static List<Message> getMessageByFriendApply(int type) {
        String[] param = {type + ""};
        String sql = "WHERE type=? and is_read=0";
        return messageDao.queryByNativeSql(sql, param);
    }

    public static List<Message> getMessage(String fromUser, String toUser, int type) {
        String[] param = {fromUser, toUser, type + ""};
        String sql = "WHERE from_user= ? and to_user = ? and type=? and is_read=0";
        return messageDao.queryByNativeSql(sql, param);
    }

    public static List<Message> getMessageByType(String phone, String type) {
        return messageDao.queryByNativeSql("where to_user=? and type=? and is_read=0", new String[]{phone, type});
    }

    public static Message getLastMessage(String fromUser, String toUser) {
        List<Message> messages = messageDao.queryByNativeSql("where from_user=? and to_user=? order by date desc limit 1",
                new String[]{fromUser, toUser});
        if (messages.size() != 0) {
            return messages.get(0);
        }
        return null;
    }

    public static List<HomeDialogueBean> getHomeDialogue(User user) {

        List<HomeDialogue> notDeleteHomeDialogues = homeDialogueDao.
                queryByNativeSql("where is_delete=? and from_user=? ", new String[]{"0", user.getPhone()});
        // 未读消息
        List<Message> messages = messageDao.queryByNativeSql("where is_read = 0 and to_user=? and type=?",
                new String[]{user.getPhone(), "1"});

        List<HomeDialogueBean> homeDialogueBeans = new ArrayList<>();

        Map<String, Message> lastMessage = new HashMap<>();
        Map<String, Integer> count = new HashMap<>();
        Map<String, Date> notDeleteHomeDialogueMap = new HashMap<>();

        for (Message message : messages) {
            String _phone = message.getFromUser();

            lastMessage.put(_phone, message);
            if (count.containsKey(_phone)) {
                count.put(_phone, count.get(_phone) + 1);
            } else {
                count.put(_phone, 1);
            }

        }

        for (HomeDialogue _notDeleteHomeDialogue : notDeleteHomeDialogues) {
            String _phone = _notDeleteHomeDialogue.getToUser();
            notDeleteHomeDialogueMap.put(_phone, _notDeleteHomeDialogue.getLastUpdate());

            if (!lastMessage.containsKey(_phone)) {
                Message _lastMessage = getLastMessage(_phone, MainActivity.user.getPhone());
                Message _lastMessage2 = getLastMessage(MainActivity.user.getPhone(), _phone);

                lastMessage.put(_phone, lastMessage(_lastMessage, _lastMessage2));
                count.put(_phone, 0);
            }

        }

        for (String key : lastMessage.keySet()) {
            if (!notDeleteHomeDialogueMap.containsKey(key)) {
                // 如果是消息对话删除 则跳过
                break;
            }

            Message message = lastMessage.get(key);
            HomeDialogueBean homeDialogueBean = new HomeDialogueBean().setFromPhone(key)
                    .setIsReadNum(count.get(key)).setLastMessage(message);
            homeDialogueBean.setLastUpdate(notDeleteHomeDialogueMap.get(key));

            homeDialogueBeans.add(homeDialogueBean);
        }

        return homeDialogueBeans;
    }

    public static void setMessageIsRead(List<Message> messages) {
        for (Message message : messages) {
            messageDao.update(message.setIsRead(1));
        }
    }

    /**
     * 判断两个时间 那个在后
     *
     * @return {@link cn.lopr.im.android.db.entity.Message}
     * @author shuangyang7
     * @date 2021/1/4 13:26
     */
    private static Message lastMessage(Message lastMessage, Message lastMessage2) {

        if (lastMessage == null && lastMessage2 == null) {
            return null;
        }
        if (lastMessage != null && lastMessage2 == null) {
            return lastMessage;
        }
        if (lastMessage2 != null && lastMessage == null) {
            return lastMessage2;
        }
        if (Objects.requireNonNull(DateUtil.formatYMDHMS(lastMessage.getDate())).
                before(DateUtil.formatYMDHMS(lastMessage2.getDate()))) {
            return lastMessage2;
        }
        return lastMessage;
    }

    public static void addMessage(List<Message> messages) {
        if (messages == null || messages.size() == 0) {
            return;
        }
        for (Message message : messages) {
            HomeDialogueDaoService.setIsDelete(message.fromUser, 0);
            message.setId(null);
            messageDao.insert(message);
        }
    }
}
